package com.example.video.service;

import com.example.video.constant.SystemConstant;
import com.example.video.util.FileToolUtil;
import com.example.video.util.VideoEncodeUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.io.File;

/**
 * @ClassName VideoMaterialService
 * @Description TODO
 * @Author Jason
 * @Date 2019/1/21 10:16
 * @Version 1.0
 **/
@Service
@Slf4j
public class VideoMaterialService {
    /**
     *
     * <p> delete temp video </p>
     * @Param tempFilePath
     * @return void
     * @date
     * @author Jason
     **/
    public void deleteVideoFile(String tempFilePath) {
        File file = new File(tempFilePath);
        if (file.exists()){
            boolean delete = file.delete();
            // file.deleteOnExit(); delete on jvm close
            if (delete){
                log.info("temporary file is deleted");
            } else {
                log.info("deleted temporary file failed");
            }
        }

    }

    /**
     * 加密视频
     * @param fileName
     */
    public void encryptVideo(String fileName){
        try {
            File file = new File(SystemConstant.VIDEO_UPLOAD_PATH);
            FileToolUtil.judeDirExists(file);
            /**
             * 加密不可进行多次
             * 判断是否有加密，加密过无需在加密
             */
            if(!VideoEncodeUtil.readFileLastByte(SystemConstant.VIDEO_UPLOAD_PATH +fileName,SystemConstant.VIDEO_ENCRYPT_DECRYPT_KEY.length()).equals(SystemConstant.VIDEO_ENCRYPT_DECRYPT_KEY)) {
                VideoEncodeUtil.encrypt(SystemConstant.VIDEO_UPLOAD_PATH  + fileName, SystemConstant.VIDEO_ENCRYPT_DECRYPT_KEY);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 解密视频 decrypt Video
     * @param fileName
     */
    public String decryptVideo(String fileName) throws Exception {

        File file = new File(SystemConstant.VIDEO_TEMP_PATH);
        FileToolUtil.judeDirExists(file);
        return VideoEncodeUtil.decrypt(SystemConstant.VIDEO_UPLOAD_PATH  + fileName,
                SystemConstant.VIDEO_TEMP_PATH + fileName,
                SystemConstant.VIDEO_ENCRYPT_DECRYPT_KEY.length());
    }
}
